from django.conf import settings
from fdfs_client.client import Fdfs_client, get_tracker_conf
from rest_framework import serializers

from goods.models import SKUImage, SKU
from celery_tasks.static_file.tasks import get_detail_html


class ImagesSerializer(serializers.ModelSerializer):
    """图片序列化器"""

    class Meta:
        model = SKUImage
        fields = "__all__"

    def create(self, validated_data):
        # 3.建立fdstdfs的客户端
        tracker_config = get_tracker_conf(settings.FASTDFS_PATH)
        client = Fdfs_client(trackers=tracker_config)
        # self.context['request']获取request对象
        file = self.context['request'].FILES.get('image')
        # 4.上传图片
        res = client.upload_by_buffer(file.read())
        # 5.判断图片是否上传成功
        if res['Status'] != 'Upload successed.':  # Status是str类型
            raise serializers.ValidationError({'error': '图片上传失败'})
        # 6.保存图片表
        # Remote file_id是字节类型
        img = SKUImage.objects.create(sku_id=self.context['request'].data.get('sku')[0], image=res['Remote file_id'].decode())
        # 异步生成详情页静态页面
        get_detail_html.delay(img.sku_id)
        # 7.返回img对象
        return img

    def update(self, instance, validated_data):
        # 3.建立fdstdfs的客户端
        tracker_config = get_tracker_conf(settings.FASTDFS_PATH)
        client = Fdfs_client(trackers=tracker_config)
        # self.context['request']获取request对象,self.context访问视图类传递过来的内容
        file = self.context['request'].FILES.get('image')
        # 4.上传图片
        res = client.upload_by_buffer(file.read())
        # 5.判断图片是否上传成功
        if res['Status'] != 'Upload successed.':  # Status是str类型
            raise serializers.ValidationError({'error': '图片上传失败'})
        # 6.更新图片表
        # Remote file_id是字节类型
        instance.image = res['Remote file_id'].decode()
        instance.save()
        # 异步生成详情页静态页面
        get_detail_html.delay(instance.sku_id)
        # 7.返回img对象
        return instance


class SkusSerializer(serializers.ModelSerializer):
    """sku商品序列化器"""
    class Meta:
        model = SKU
        fields = ('id', 'name')
